package com.lxy.cxcyxmmsbackend.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxy.cxcyxmmsbackend.sys.entity.*;
import com.lxy.cxcyxmmsbackend.sys.exceptionHandle.exce.NormalException;
import com.lxy.cxcyxmmsbackend.sys.req.PageReq;
import com.lxy.cxcyxmmsbackend.sys.res.Result;

import com.lxy.cxcyxmmsbackend.sys.service.KeyValueService;
import com.lxy.cxcyxmmsbackend.sys.service.XmHjqkService;
import com.lxy.cxcyxmmsbackend.sys.utils.UUIDUtil;
import com.lxy.cxcyxmmsbackend.sys.utils.UpPhotoNameUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 刘新颖
 * @since 2024-01-27
 */
@Api(tags = "项目获奖情况")
@RestController
@RequestMapping("/xmHjqk")
public class XmHjqkController {

    @Autowired
    XmHjqkService xmHjqkService;

    @Autowired
    Environment environment;

    @Autowired
    KeyValueService keyValueService;

    @ApiOperation("查询项目获奖情况记录")
    @PostMapping("/queryXmHjjl")
    public Result queryXmHjjl(@RequestBody PageReq pageReq) {
        Integer pageNo = pageReq.getCurrentPage();
        Integer pageSize = pageReq.getPageSize();
        Page<XmHjqk> pages = new Page<>(pageReq.getCurrentPage(), pageReq.getPageSize());
        QueryWrapper<XmHjqk> wrapper = new QueryWrapper<>();

        String xmmc = pageReq.getKeyWord().get("xmmc");

        //项目名称
        if (xmmc != null && !"".equals(xmmc)) {
            wrapper.lambda().like(XmHjqk::getXmMc, xmmc);
        }

        String bsmc = pageReq.getKeyWord().get("bsmc");

        //项目名称
        if (bsmc != null && !"".equals(bsmc)) {
            wrapper.lambda().like(XmHjqk::getBsMc, bsmc);
        }

        String bsJb = pageReq.getKeyWord().get("bsJb");
        if (bsJb != null && !"".equals(bsJb)) {
            wrapper.lambda().like(XmHjqk::getBsJb, bsJb);
        }
        String dj = pageReq.getKeyWord().get("dj");

        if (dj != null && !"".equals(dj)) {
            wrapper.lambda().like(XmHjqk::getDj, dj);
        }

        wrapper.orderByDesc("HJSJ");

        IPage<XmHjqk> page = xmHjqkService.page(pages, wrapper);

        HashMap<Object, Object> map = new HashMap<>();

        map.put("pageNo", pageNo);
        map.put("pageSize", pageSize);
        List<XmHjqk> records = page.getRecords();

        map.put("rows", records);
        map.put("total", page.getTotal());
        map.put("pageNums", (int) Math.ceil((double) page.getTotal() / pageSize));

        return Result.success("查询项目获奖情况成功", map);
    }

    @SneakyThrows
    @ApiOperation("新增项目空间打扫记录")
    @PostMapping("/saveXmhjqk")
    public Result saveXmhjqk(@RequestBody XmHjqk xmHjqk) {
        String id = xmHjqk.getId();
        if ("".equals(id) || id == null) {

            xmHjqk.setId(UUIDUtil.getUUID8("H", 8));


            QueryWrapper<KeyValue> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(KeyValue::getKeycode,"bsjb");
            wrapper.lambda().eq(KeyValue::getKeyvalue,xmHjqk.getBsJb());
            KeyValue bsjb = keyValueService.getOne(wrapper);
            xmHjqk.setBsJbmc(bsjb.getKeyname());
            wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(KeyValue::getKeycode,"hjdj");
            wrapper.lambda().eq(KeyValue::getKeyvalue,xmHjqk.getDj());
            KeyValue hjdj = keyValueService.getOne(wrapper);
            xmHjqk.setDjmc(hjdj.getKeyname());
            xmHjqk.setHjzm("img.png");
            xmHjqk.setStatus("0");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            Date parse = simpleDateFormat.parse(xmHjqk.getHjsj());
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            xmHjqk.setHjsj(simpleDateFormat.format(parse));
            boolean save = xmHjqkService.save(xmHjqk);
            if (!save) {
                throw new NormalException("新增项目获奖情况失败");
            }
        } else {
            QueryWrapper<KeyValue> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(KeyValue::getKeycode,"bsjb");
            wrapper.lambda().eq(KeyValue::getKeyvalue,xmHjqk.getBsJb());
            KeyValue bsjb = keyValueService.getOne(wrapper);
            xmHjqk.setBsJbmc(bsjb.getKeyname());
            wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(KeyValue::getKeycode,"hjdj");
            wrapper.lambda().eq(KeyValue::getKeyvalue,xmHjqk.getDj());
            KeyValue hjdj = keyValueService.getOne(wrapper);
            xmHjqk.setDjmc(hjdj.getKeyname());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            Date parse = simpleDateFormat.parse(xmHjqk.getHjsj());
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            xmHjqk.setHjsj(simpleDateFormat.format(parse));
            boolean save = xmHjqkService.updateById(xmHjqk);
            if (!save) {
                throw new NormalException("修改项目获奖情况失败");
            }
        }

        return Result.success("保存项目获奖情况成功", null);
    }

    @ApiOperation("查询项目获奖记录详情")
    @PostMapping("/getXmhjqkDetail/{id}")
    @Transactional
    public Result getXmhjqkDetail(@PathVariable("id") String id) {
        XmHjqk xmHjqk = xmHjqkService.getById(id);
        if (xmHjqk == null) {
            throw new NormalException("查询项目获奖记录详情失败");
        }
        return Result.success("查询项目获奖记录详情成功", xmHjqk);
    }

    @ApiOperation("审批项目获奖记录")
    @PostMapping("/approvalXmhjqk/{id}")
    @Transactional
    public Result approvalXmhjqk(@PathVariable("id") String id) {
        XmHjqk xmHjqk = xmHjqkService.getById(id);
        xmHjqk.setStatus("2");
        boolean save = xmHjqkService.updateById(xmHjqk);
        if (!save) {
            throw new NormalException("审批项目获奖情况失败");
        }
        return Result.success("审批项目获奖情况成功", xmHjqk);
    }

    @ApiOperation("提交项目获奖记录")
    @GetMapping("/tjXmhjqk/{id}")
    @Transactional
    public Result tjXmhjqk(@PathVariable("id") String id) {
        XmHjqk xmHjqk = xmHjqkService.getById(id);
        xmHjqk.setStatus("1");
        boolean save = xmHjqkService.updateById(xmHjqk);
        if (!save) {
            throw new NormalException("提交项目获奖情况失败");
        }
        return Result.success("提交项目获奖情况成功", xmHjqk);
    }

    @ApiOperation("驳回项目获奖记录")
    @PostMapping("/cancelXmhjqk/{id}")
    @Transactional
    public Result cancelXmhjqk(@RequestBody XmHjqk xmHjqk) {
        xmHjqk.setStatus("-1");
        boolean save = xmHjqkService.updateById(xmHjqk);
        if (!save) {
            throw new NormalException("审批项目获奖情况失败");
        }
        return Result.success("审批项目获奖情况成功", xmHjqk);
    }

    @ApiOperation("删除项目获奖情况")
    @PostMapping("/removeXmhjqk/{id}")
    @Transactional
    public Result removeXmhjqk(@PathVariable("id") String id) {
        boolean remove = xmHjqkService.removeById(id);
        if (!remove) {
            throw new NormalException("删除项目获奖情况失败");
        }
        return Result.success("删除项目获奖情况成功", null);
    }

    @ApiOperation("提交项目获奖情况")
    @PostMapping("/tijiaoXmhjqk/{id}")
    @Transactional
    public Result tijiaoXmhjqk(@PathVariable("id") String id) {
        XmHjqk xmHjqk = xmHjqkService.getById(id);
        xmHjqk.setStatus("1");
        boolean save = xmHjqkService.updateById(xmHjqk);
        if (!save) {
            throw new NormalException("提交项目获奖情况失败");
        }
        return Result.success("提交项目获奖情况成功", xmHjqk);
    }

    @ApiOperation("上传获奖证明")
    @RequestMapping("uploadHjzm")
    public String uploadTX(@RequestParam("file") MultipartFile file, HttpServletRequest request, String id) {
        XmHjqk xmHjqk  = xmHjqkService.getById(id);

        try {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtils.getPhotoName("img", imageFileName);
            String url = environment.getProperty("front-assert-url.hjzm");
            Path path = Paths.get(url + fileName);

            File file1 = new File(url + xmHjqk.getHjzm());
            if (file1.exists() && !xmHjqk.getHjzm().equals("img.png")){
                if (file1.delete()){
                    System.out.println(xmHjqk.getHjzm() + "图片删除成功！");
                }
            }
            Files.write(path, bytes);//写入文件
            String avatar_url = fileName;
            xmHjqk.setHjzm(avatar_url);
            boolean b = xmHjqkService.updateById(xmHjqk);
            System.out.println(fileName + "\n");
            return fileName;//返回文件名字
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}

